#define _CRT_SECURE_NO_WARNINGS 1


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* _buildTree(vector<int>& inorder, vector<int>& postorder, int& posi, int inbegin, int inend)
    {
        if (inbegin >= inend)
            return nullptr;

        TreeNode* root = new TreeNode(postorder[posi]);
        int i;
        for (i = inbegin; i < inend; i++)
        {
            if (postorder[posi] == inorder[i])
                break;
        }
        posi--;
        root->right = _buildTree(inorder, postorder, posi, i + 1, inend);
        root->left = _buildTree(inorder, postorder, posi, inbegin, i);

        return root;
    }
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        int posi = inorder.size() - 1;
        return _buildTree(inorder, postorder, posi, 0, inorder.size());
    }
};